import os
import base64
import requests
import numpy as np
from PIL import Image
from io import BytesIO
from collections import defaultdict
from api_base64 import process_image

 
def process_stamp(PIPELINE_SEAL, process_image_result):
    all_stamp = []
    
    if not process_image_result or 'category_data' not in process_image_result:
        print("无效的 process_image 结果")
        return all_stamp
    
    stamp_data = process_image_result['category_data'].get('stamp', [])
    
    for stamp_item in stamp_data:
        try:
            img_array = stamp_item['array']
            output = PIPELINE_SEAL.predict(
                img_array, 
                use_doc_orientation_classify=True,
                use_doc_unwarping=True,
            )
            
            for res in output:
                # res['orin_position'] = stamp_item['position']
                all_stamp.append(res)
                    
        except Exception as e:
            print(f"处理印章数据时出错: {str(e)}")
            continue
            
    return all_stamp


if __name__ == "__main__":
    from paddlex import create_model, create_pipeline
    PIPELINE_SEAL = create_pipeline(pipeline="seal_recognition")   
    with open("test.jpg", "rb") as f:
        real_base64 = base64.b64encode(f.read()).decode('utf-8')
    result = process_image(real_base64)
    stamp_results = process_stamp(PIPELINE_SEAL, result)




## stamp_test.py 是从 main_process.py 中抽离 process_stamp 函数的测试代码
## 当前代码修改了模型入参方式，之前是直接传入图片路径，现在是传入numpy数组
## 但修改入参方式之后，模型最后的输出all_stamp中的 “layout_det_res” 和 “rec_texts” 字段缺失，需要进一步排查

